﻿using UnityEngine;
using System.Collections;
using System;
using UnityEngine.UI;
using System.Reflection;
using UnityEngine.Events;

namespace Titan.UI
{
    public class ButtonT : Button
    {
        #region Public Attributes
        public MsgOption m_clickMsg = new MsgOption();
        #endregion

        #region Private Attributes

        #endregion

        #region Public Methods
       
        #endregion

        #region Override Methods

        public override void OnPointerClick(UnityEngine.EventSystems.PointerEventData eventData)
        {
            base.OnPointerClick(eventData);
            SendMsg();
        }
        #endregion

        #region Private Methods
        protected virtual void SendMsg()
        {
            var callEvent = m_clickMsg.callEvent;
            string msgMethodName = callEvent.MethodName;
            MethodInfo method = null;
            if (msgMethodName.Length > 0)
            {
                method = UnityEventBase.GetValidMethodInfo(callEvent.Script, msgMethodName, new Type[] { Type.GetType(callEvent.ParamType), typeof(UnityEngine.Object) });
                if(method == null)
                {
                    Debug.LogError("Can't find Call Method ["+msgMethodName+"]");
                }                    
            }
            
            var dataEvent = m_clickMsg.dataEvent;
            switch (dataEvent.DataType)
            {
                case DataEvent.ConstDataType.None:
                    method.Invoke(callEvent.Script, new System.Object[] {null,callEvent.ParamObj });
                    break;
                case DataEvent.ConstDataType.Customer:
                    string dataMethodName = dataEvent.MethodName;
                    if (dataMethodName.Length > 0)
                    {
                        MethodInfo dataMethod = UnityEventBase.GetValidMethodInfo(dataEvent.Script, dataMethodName, new Type[] { typeof(UnityEngine.Object)});
                        if(dataMethod == null)
                        {
                            Debug.LogError("Can't find data Method ["+dataMethod+"]");
                        }
                        var returnType = dataMethod.Invoke(dataEvent.Script, new System.Object[] { dataEvent.ParamObj });
                        method.Invoke(callEvent.Script, new System.Object[] {(UIEventArgs)returnType,callEvent.ParamObj });
                    }
                    else
                    {
                        Debug.LogError("MethodName Error! No Method [ " + m_clickMsg.callEvent.MethodName + " ] in [" + m_clickMsg.callEvent.Target + "]");
                    }
                    break;
                default:
                    Debug.LogError("dataEvent.DataType Error! Type is [ " + dataEvent.DataType + " ] ");
                    break;
            }
        }

        #endregion

        #region Inner
        #endregion
    }
}
